package com.android.functionmanagement.util;

import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.Locale;

import com.android.functionmanagement.globle.ConstantGloble;

import android.content.Context;
import android.util.Log;

public class GatherDataUtil {

	private static final String TAG = "yantm";
	public static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
	
	public static void sendGatherData(Context context) {
		
		int stepCount = getStepCount(context);
		String heartRate = SharedPreferencesUtils.getParam(context, ConstantGloble.HEARTRATE_DATA, "").toString();
		Log.e(TAG, " stepCount = " + stepCount + " heartRate = " + heartRate);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
		String time = format.format(System.currentTimeMillis());
		if (DeviceUtils.haveInternet(context)) {
			// 发送当前数据
			// 检查未发送数据并发送
			HashSet<String> unsendDataSet = (HashSet<String>) SharedPreferencesUtils.getParam(context,
					ConstantGloble.UNSEND_GATHER_DATA, new HashSet<String>());
			if (unsendDataSet != null && unsendDataSet.size() > 0) {
				HashSet<String> tempSet = new HashSet<String>(unsendDataSet);
				Log.e(TAG, " before unsendDataSet = " + unsendDataSet);
				for (String unsendData : tempSet) {
					// 发送数据
					Log.e(TAG, unsendData);
					// 发送完毕移除
					unsendDataSet.remove(unsendData);
				}
				SharedPreferencesUtils.setParam(context, ConstantGloble.UNSEND_GATHER_DATA, unsendDataSet);
				Log.e(TAG, " after unsendDataSet = " + unsendDataSet);
			}
		} else {
			// 保存本地
			HashSet<String> unsendDataSet = (HashSet<String>) SharedPreferencesUtils.getParam(context,
					ConstantGloble.UNSEND_GATHER_DATA, new HashSet<String>());
			Log.e(TAG,
					" data = " + unsendDataSet + " size = " + (unsendDataSet != null ? unsendDataSet.size() : 0));
			String sendMsg = time + "," + heartRate + "," + stepCount;
			unsendDataSet.add(sendMsg);
			Log.e(TAG, "after add size = " + unsendDataSet.size());
			SharedPreferencesUtils.setParam(context, ConstantGloble.UNSEND_GATHER_DATA, unsendDataSet);
		}
	}

	private static int getStepCount(Context context) {
		int step = StepOpenHelper.getInstance(context).getStepCount(
				getCurrentDate());
		return step;
	}

	private static String getCurrentDate() {
		return df.format(System.currentTimeMillis());
	}
}
